<?php
/**
 *    前台控制器基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class FrontendApp extends ECBaseApp
{
    function __construct()
    {
        $this->FrontendApp();
    }
    function FrontendApp()
    {
    	Lang::load(lang_file('common'));
        Lang::load(lang_file(APP));
        parent::__construct();
        
        // 判断商城是否关闭
        if (!Conf::get('site_status'))
        {
            $this->show_warning(Conf::get('closed_reason'));
            exit;
        }
        # 在运行action之前，无法访问到visitor对象
    }
    function _config_view()
    {
        parent::_config_view();
        /*$this->_view->template_dir  = ROOT_PATH . '/themes';
        $this->_view->compile_dir   = ROOT_PATH . '/temp/compiled/mall';
        $this->_view->res_base      = SITE_URL . '/themes';
        $this->_config_seo(array(
            'title' => Conf::get('site_title'),
            'description' => Conf::get('site_description'),
            'keywords' => Conf::get('site_keywords')
        ));*/
        $this->_view->template_dir  = ROOT_PATH . '/template';
        $this->_view->compile_dir   = ROOT_PATH . '/template/compiled';
        $this->_view->res_base      = SITE_URL . '/template';
        $this->_config_seo(array(
            'title' => Conf::get('site_title'),
            'description' => Conf::get('site_description'),
            'keywords' => Conf::get('site_keywords')
        ));
    }
    function display($tpl)
    {
        $this->assign('site_title', Conf::get('site_title'));
        parent::display($tpl);
    }
    function login()
    {
        if ($this->visitor->has_login)
        {
            header('location:index.php');
        }
		
        if (!IS_POST)
        {
            if (!empty($_GET['ret_url']))
            {
                $ret_url = trim($_GET['ret_url']);
            }
            else
            {
                if (isset($_SERVER['HTTP_REFERER']))
                {
                    $ret_url = $_SERVER['HTTP_REFERER'];
                }
                else
                {
                    $ret_url = SITE_URL . '/index.php';
                }
            }
            /* 防止登陆成功后跳转到登陆、退出的页面 */
            $ret_url = strtolower($ret_url);            
            if (str_replace(array('act=login', 'act=logout',), '', $ret_url) != $ret_url)
            {
                $ret_url = SITE_URL . '/index.php';
            }

            if (Conf::get('captcha_status.login'))
            {
                $this->assign('captcha', 1);
            }
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
            $this->assign('ret_url', rawurlencode($ret_url));
            //$this->_curlocal(LANG::get('user_login'));
            $this->_config_seo('title', Lang::get('user_login') . ' - ' . Conf::get('site_title'));
            if ($_GET['lang']){
            	$this->display('login.en.html');
            }else{
            	$this->display('login.index.html');
            }
            /* 同步退出外部系统 */
            if (!empty($_GET['synlogout']))
            {
                $ms =& ms();
                echo $synlogout = $ms->user->synlogout();
            }
        }
        else
        {
            if (Conf::get('captcha_status.login') && base64_decode($_SESSION['captcha']) != strtolower($_POST['captcha']))
            {
                $this->show_warning('captcha_failed');

                return;
            }

            $user_name = trim($_POST['user_name']);
            $password  = $_POST['password'];

            $ms =& ms();
            $user_id = $ms->user->auth($user_name, $password);
            if (!$user_id)
            {
                /* 未通过验证，提示错误信息 */
                $this->show_warning($ms->user->get_error());

                return;
            }
            else
            {
                /* 通过验证，执行登陆操作 */
                $this->_do_login($user_id);

                /* 同步登陆外部系统 */
                $synlogin = $ms->user->synlogin($user_id);
            }

            /*$this->show_message(Lang::get('login_successed') . $synlogin,
                'back_before_login', rawurldecode($_POST['ret_url']),
                'enter_member_center', 'index.php?app=member'
            );*/
			header('location:index.php');
        }
    }

    function pop_warning ($msg, $dialog_id = '',$url = '')
    {
        if($msg == 'ok')
        {
            if(empty($dialog_id))
            {
                $dialog_id = APP . '_' . ACT;
            }
            if (!empty($url))
            {
                echo "<script type='text/javascript'>window.parent.location.href='".$url."';</script>";
            }
            echo "<script type='text/javascript'>window.parent.js_success('" . $dialog_id ."');</script>";
        }
        else
        {
            header("Content-Type:text/html;charset=".CHARSET);
            $msg = is_array($msg) ? $msg : array(array('msg' => $msg));
            $errors = '';
            foreach ($msg as $k => $v)
            {
                $error = $v[obj] ? Lang::get($v[msg]) . " [" . Lang::get($v[obj]) . "]" : Lang::get($v[msg]);
                $errors .= $errors ? "<br />" . $error : $error;
            }
            echo "<script type='text/javascript'>window.parent.js_fail('" . $errors . "');</script>";
        }
    }

    function logout()
    {
        $this->visitor->logout();

        /* 跳转到登录页，执行同步退出操作 */
        header("location: index.php?app=default&act=login");
        return;
    }

    /* 执行登录动作 */
    function _do_login($user_id)
    {
        $mod_user =& m('member');

        $user_info = $mod_user->get(array(
        	'join'			=> 'has_consumer,has_factory',
            'conditions'    => "member.user_id = '{$user_id}'",
            'fields'        => 'member.user_id, user_name,is_factory,factory_info.factory_id,factory_info.factory_name,activation,role,role_cate,is_vip,country',
        ));
		
		if (!$_COOKIE['login_user']) {
			setcookie('login_user', $user_id, time() + 8 * 3600);
		}
		if (in_array($user_info['role'], array(USER_CLIENT,USER_FACTORY,USER_MERCHANT))){
			if (!$user_info['activation']){
				$this->display('member.activation.html');
				exit;
			}
		}
        /* 分派身份 */
        $this->visitor->assign($user_info);
    }

    /* 取得导航 */
    function _get_navs()
    {
        $cache_server =& cache_server();
        $key = 'common.navigation';
        $data = $cache_server->get($key);
        if($data === false)
        {
            $data = array(
                'header' => array(),
                'middle' => array(),
                'footer' => array(),
            );
            $nav_mod =& m('navigation');
            $rows = $nav_mod->find(array(
                'order' => 'type, sort_order',
            ));
            foreach ($rows as $row)
            {
                $data[$row['type']][] = $row;
            }
            $cache_server->set($key, $data, 86400);
        }

        return $data;
    }

    /**
     *    获取JS语言项
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function jslang()
    {
        $lang = Lang::fetch(lang_file('jslang'));
        parent::jslang($lang);
    }

    /**
     *    视图回调函数[显示小挂件]
     *
     *    @author    Garbin
     *    @param     array $options
     *    @return    void
     */
    function display_widgets($options)
    {
        $area = isset($options['area']) ? $options['area'] : '';
        $page = isset($options['page']) ? $options['page'] : '';
        if (!$area || !$page)
        {
            return;
        }
        include_once(ROOT_PATH . '/includes/widget.base.php');

        /* 获取该页面的挂件配置信息 */
        $widgets = get_widget_config($this->_get_template_name(), $page);

        /* 如果没有该区域 */
        if (!isset($widgets['config'][$area]))
        {
            return;
        }

        /* 将该区域内的挂件依次显示出来 */
        foreach ($widgets['config'][$area] as $widget_id)
        {
            $widget_info = $widgets['widgets'][$widget_id];
            $wn     =   $widget_info['name'];
            $options=   $widget_info['options'];

            $widget =& widget($widget_id, $wn, $options);
            $widget->display();
        }
    }

    /**
     *    获取当前使用的模板名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_template_name()
    {
        return 'default';
    }

    /**
     *    获取当前使用的风格名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_style_name()
    {
        return 'default';
    }

    /**
     *    当前位置
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _curlocal($arr)
    {
        $curlocal = array(array(
            'text'  => Lang::get('index'),
            'url'   => SITE_URL . '/index.php',
        ));
        if (is_array($arr))
        {
            $curlocal = array_merge($curlocal, $arr);
        }
        else
        {
            $args = func_get_args();
            if (!empty($args))
            {
                $len = count($args);
                for ($i = 0; $i < $len; $i += 2)
                {
                    $curlocal[] = array(
                        'text'  =>  $args[$i],
                        'url'   =>  $args[$i+1],
                    );
                }
            }
        }

        //$this->assign('_curlocal', $curlocal);
		$script_str = '<script type="text/javascript">if (top == self) {curlocal(arr);} else {window.parent.curlocal(arr);}</script>';
		$script_arr = 'new Array(';
		foreach ($curlocal as $item) {
			$script_arr .= 'new Array("' . $item['text'] . '", "' . $item['url'] . '"), ';
		}
		$script_arr = substr($script_arr, 0, strlen($script_arr) - 2) . ')';
		$script_str = str_replace('arr', $script_arr, $script_str);
		echo $script_str;
    }
    function _init_visitor()
    {
        $this->visitor =& env('visitor', new UserVisitor());
    }
	
	/* 文件上传默认设置 */
	function _default_upload_setting()
	{
		$setting['root_dir'] = ROOT_PATH . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR;
		
		$setting['sample'] = array(
			'img' => 'sample' . DIRECTORY_SEPARATOR . '{sample_id}' . DIRECTORY_SEPARATOR,
			'color_card' => 'sample' . DIRECTORY_SEPARATOR . '{sample_id}' . DIRECTORY_SEPARATOR,
			'factory' => 'sample' . DIRECTORY_SEPARATOR . '{sample_id}' . DIRECTORY_SEPARATOR,
		);
		
		$setting['order'] = array(
			'img' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
			'fabric' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
			'pigai' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
			'hetong' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
			'zhidan' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
			'chahuo' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
			'koukuan' => 'order' . DIRECTORY_SEPARATOR . '{order_id}' . DIRECTORY_SEPARATOR,
		);
		
		$setting['other'] = array(
			'news_img' => 'news' . DIRECTORY_SEPARATOR . '{news_id}' . DIRECTORY_SEPARATOR,
			'news_files' => 'news' . DIRECTORY_SEPARATOR . '{news_id}' . DIRECTORY_SEPARATOR,
		);
		
		return $setting;
	}
	
	/* 获取文件上传设置 */
	function _get_upload_setting()
	{
		$cache_server =& cache_server();
		$key = 'upload_setting';
		$setting = $cache_server->get($key);
		if (!$setting) {
			$setting = $this->_default_upload_setting();
		}
		return $setting;
	}
	
	/* 检查权限 */
	/* @param $roles 有权限的角色 */
	function check_powers($roles,$out=true) {
		return true;   //废弃此权限功能
		$role = $this->visitor->get('role');
		$roles = is_array($roles) ? $roles : array($roles);
		//print_r($role)."<br>".print_r($roles);
		if (!in_array($role, $roles)) {
                    if($out){
                        if(!IS_AJAX){
                        $this->show_warning('no_powers_to_visit');
			exit;
                        }
                        else{
                            $this->json_error(Lang::get('no_powers_to_visit'));
                            exit;
                        }
                    }
                    else{
                        return false;
                    }
		}
                return true;
	}
	
	/* 品牌列表 */
	function _assign_brand_list()
	{
		$brand_mod =& m('brand');
		$brand_list = $brand_mod->find(array(
			'conditions' => 'if_show = 1',
			'join'	=>'belong_company',
			'order' => 'brand_name ASC',
		));
		$this->assign('brand_list', $brand_list);
	}

        /* 品牌列表 */
	function _assign_factory_list()
	{
		$factory_mod =& m('factory_info');
		$this->assign('factory_list', $factory_mod->find(array('conditions'=>'if_show = 1 and activation=1', 'order'=>'factory_name', 'join'=>'belongs_factory_member')));
	}
	
	/* 品牌买手联动 */
	function AjaxBuyerByBrand()
	{
		$brand_id = isset($_GET['brand_id']) ? intval($_GET['brand_id']) : 0;
		$buyer_mod =& m('member');
		$brand_mod =& m('brand');
		$brand_info=$brand_mod->get($brand_id);
		if ($this->visitor->get('role')==USER_CLIENT){
			$buyer_list = $buyer_mod->find(array(
					'fields' => 'user_id, user_name',
					'conditions' => 'member.if_show = 1 and member.activation=1 AND member.company_id = ' . $brand_info['company_id'].' and FIND_IN_SET('.$brand_id.',brand_arr_id) and user_id='.$this->visitor->get('user_id'),
					'order' => 'user_name ASC',
			));
		}else{
			$buyer_list = $buyer_mod->find(array(
					'fields' => 'user_id, user_name',
					'conditions' => 'member.if_show = 1 and member.activation=1 AND member.company_id = ' . $brand_info['company_id'].' and FIND_IN_SET('.$brand_id.',brand_arr_id)',
					'order' => 'user_name ASC',
			));
		}
		$arr = array();
		$arr['list'] = $buyer_list;
		
		$arr['addr'] = $brand_info['brand_addr'];
		$main_mod=&m('main_label');
		$main_list=$main_mod->find(array(
				'conditions'=>'brand_id='.$brand_id,
				'order'=>'m_id desc'
		));
		$listing_mod=&m('listing');
		$listing=$listing_mod->find(array(
				'conditions'=>'brand_id='.$brand_id,
				'order'=>'listing_time desc'
		));
		$arr['listing']=$listing;
		$arr['main_list']=$main_list;
		exit(json_encode($arr));
	}
	
	/* 买手跟单联动 */
	function AjaxMerchByBuyer()
	{
		$buyer_id = isset($_GET['buyer_id']) ? intval($_GET['buyer_id']) : 0;
		$buyer_mod =& m('member');
		$buyer_info = current($buyer_mod->find(array(
			'fields' => 'freight_id',
			'conditions' => 'member.user_id = ' . $buyer_id . ' AND member.if_show = 1',
			//'join' => 'belongs_merchandiser',
			'order' => 'member.user_name ASC',
		)));
		header("Content-type: text/html; charset=" . CHARSET);
		if (!empty($buyer_info)){
			$buyer=$buyer_mod->get(array(
				'conditions'=>'user_id='.$buyer_info['freight_id'],
				'fields'	=>'user_id,user_name',
				'order'		=>'user_name asc'		
			));
		}
		if (!empty($buyer)) {
			echo $buyer['user_id'] . ',' . $buyer['user_name'];
		}
	}
	
	function create_sourcing_list_sn()
	{
		return 'PR'.date('YmdHis');
	}
}
/**
 *    前台访问者
 *
 *    @author    Garbin
 *    @usage    none
 */
class UserVisitor extends BaseVisitor
{
    var $_info_key = 'user_info';

    /**
     *    退出登录
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function logout()
    {
        /* 将购物车中的相关项的session_id置为空 */
        /*$mod_cart =& m('cart');
        $mod_cart->edit("user_id = '" . $this->get('user_id') . "'", array(
            'session_id' => '',
        ));*/

        /* 退出登录 */
        parent::logout();
    }
}
/**
 *    商城控制器基类
 *
 *    @author    Garbin
 *    @usage    none
 */
class MallbaseApp extends FrontendApp
{
    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && in_array(APP, array('apply')))
        {
            header('Location: index.php?app=default&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

            return;
        }

        parent::_run_action();
    }

    function _config_view()
    {
        parent::_config_view();

        /*$template_name = $this->_get_template_name();
        $style_name    = $this->_get_style_name();

        $this->_view->template_dir = ROOT_PATH . "/themes/mall/{$template_name}";
        $this->_view->compile_dir  = ROOT_PATH . "/temp/compiled/mall/{$template_name}";
        $this->_view->res_base     = SITE_URL . "/themes/mall/{$template_name}/styles/{$style_name}";*/
        $this->_view->template_dir = ROOT_PATH . "/template";
        $this->_view->compile_dir  = ROOT_PATH . "/template/compiled";
        $this->_view->res_base     = SITE_URL . "/template/style";

    }


    /* 取得支付方式实例 */
    function _get_payment($code, $payment_info)
    {
        include_once(ROOT_PATH . '/includes/payment.base.php');
        include(ROOT_PATH . '/includes/payments/' . $code . '/' . $code . '.payment.php');
        $class_name = ucfirst($code) . 'Payment';

        return new $class_name($payment_info);
    }

    /**
     *   获取当前所使用的模板名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_template_name()
    {
        $template_name = Conf::get('template_name');
        if (!$template_name)
        {
            $template_name = 'default';
        }

        return $template_name;
    }

    /**
     *    获取当前模板中所使用的风格名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_style_name()
    {
        $style_name = Conf::get('style_name');
        if (!$style_name)
        {
            $style_name = 'default';
        }

        return $style_name;
    }
}

/**
 *    购物流程子系统基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class ShoppingbaseApp extends MallbaseApp
{
    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && !in_array(ACT, array('login', 'register', 'check_user','factory_register','go_register','merch_register')))
        {
			if ($_COOKIE['login_user']) {
				$this->_do_login($_COOKIE['login_user']);
			}
            if (!IS_AJAX)
            {
                header('Location:index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

                return;
            }
            else
            {
                $this->json_error('login_please');
                return;
            }
        }

        parent::_run_action();
    }
}

/**
 *    用户中心子系统基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class MemberbaseApp extends MallbaseApp
{

    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && !in_array(ACT, array('login', 'register', 'check_user','check_email','factory_register','newupload','delete','jslang','go_register','merch_register')))
        {
			
            if (!IS_AJAX)
            {
                header('Location:index.php?app=default&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

                return;
            }
            else
            {
                $this->json_error('login_please');
                return;
            }
        }

        parent::_run_action();
    }
    /**
     *    当前选中的菜单项
     *
     *    @author    Garbin
     *    @param     string $item
     *    @return    void
     */
    function _curitem($item)
    {
		$_member_menu=$this->_get_member_menu();
		//菜单根据用户权限显示
		$roles=LANG::GET("roles");
		$role=$roles[$this->visitor->get('role')];
		$all_role_acl=include(ROOT_PATH . '/includes/access/roles.config.php');
		$role_acl=explode(",",$all_role_acl[$role]);
		$this->_filter_menu_byacc($_member_menu,$role_acl);
		$this->_filter_menu_byacc($_member_menu,$role_acl);
		$this->_filter_menu_byacc($_member_menu,$role_acl);
        $this->assign('_member_menu',$_member_menu);
        $this->assign('_curitem', $item);
    }
	
	//根据用户权限过滤菜单
	function _filter_menu_byacc(&$_member_menu,$role_acl)
	{	
		foreach($_member_menu as $key=>$item)
		{
			if(isset($item['app']))
			{
				$item_act=isset($item['act'])?$item['act']:"index";
				if(!in_array("{$item['app']}_{$item_act}",$role_acl))
				{
					unset($_member_menu[$key]);
				}
			}
			else
			{
				if(isset($item['submenu'])&&!empty($item['submenu']))
				{	
				$this->_filter_menu_byacc($_member_menu[$key]['submenu'],$role_acl);
				}
				else
				{
				unset($_member_menu[$key]);
				}
			}
			

		}
		
	//	return $_member_menu;
	}
	
    /**
     *    当前选中的子菜单
     *
     *    @author    Garbin
     *    @param     string $item
     *    @return    void
     */
    function _curmenu($item)
    {
        $_member_submenu = $this->_get_member_submenu();
        foreach ($_member_submenu as $key => $value)
        {
            $_member_submenu[$key]['text'] = $value['text'] ? $value['text'] : Lang::get($value['name']);
        }

        $this->assign('_member_submenu', $_member_submenu);
        $this->assign('_curmenu', $item);
    }
    /**
     *    获取子菜单列表
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _get_member_submenu()
    {
        return array();
    }
    /**
     *    获取用户中心全局菜单列表
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _get_member_menu()
    {
        $menu = array();
             /* qita */
//         $menu_other=array(
//                 'style_manage'  => array(
//                     'text'  => Lang::get('style_manage'),
//                     'app'   => 'style',
//                     'name'  => 'style_manage',
//                 ),
        		
// 				/*'fabric_manage' => array(
// 					'text' => Lang::get('fabric_manage'),
// 					'app' => 'fabric',
// 					'name' => 'fabric_manage'
// 				),
// 				'feature_manage' => array(
// 					'text' => Lang::get('feature_manage'),
// 					'app' => 'feature',
// 					'name' => 'feature'
// 				),
//                 'special_manage' =>array(
//                     'text'  => Lang::get('special_manage'),
//                     'app'   => 'special',
//                     'name'  => 'special_manage',

//                 )*/
//         );

		/* 信息发布 */
		$menu['news_manage'] = array(
			'name'		=> 'news_manage',
			'text'		=> Lang::get('news_manage'),
			'submenu'	=> array(
				'add_news'	=> array(
					'text'	=> Lang::get('add_news'),
					'app'	=> 'news',
					'act'	=> 'add',
					'name'	=> 'member',
				),
				'history_news'		=> array(
					'text'	=> Lang::get('history_news'),
					'app'	=> 'news',
					'name'	=> 'buyer',
				)
			)
		);
		
		
		/* 待审管理 */
		$menu['approve_manage'] = array(
				'name'		=> 'approve_manage',
				'text'		=> Lang::get('approve_manage'),
				'submenu'	=> array(
						'sample_approve'  => array(
								'text'  => Lang::get('sample_approve'),
								'app'   => 'sample',
								'act'	=> 'approve',
								'name'  => 'sample_approve',
						),
						'order_approve'  => array(
								'text'  => Lang::get('order_approve'),
								'app'   => 'order',
								'name'  => 'order_approve',
								'act'  => 'approve',
						),
						'order_ssapprove'  => array(
								'text'  => Lang::get('order_ssapprove'),
								'app'   => 'order',
								'name'  => 'order_ssapprove',
								'act'  => 'ssapprove',
						),
						'order_ssapproved'  => array(
								'text'  => Lang::get('order_ssapproved'),
								'app'   => 'order',
								'name'  => 'order_ssapproved',
								'act'  => 'ssapproved',
						),
						'evaluate_list'	=> array(
								'text'	=> Lang::get('evaluate_list'),
								'app'	=> 'evaluate',
								'act'	=> 'index',
						),
						'order_quote_approve'  => array(
								'text'  => Lang::get('order_quote_approve'),
								'app'   => 'order',
								'name'  => 'order_quote_approve',
								'act'  => 'quote_approve',
						),
						'color_approve'  => array(
								'text'  => Lang::get('color_approve'),
								'app'   => 'colorcard',
								'name'  => 'color_approve',
								'act'  => 'appove_color',
						),
						'merchant_approve'  => array(
								'text'  => Lang::get('merchant_approve'),
								'app'   => 'merchant',
								'name'  => 'merchant_approve',
								'act'  => 'fabric_approve',
						)
				)
		);
		
		
		/* 工厂报价管理 */
		$menu['quote_manage'] = array(
				'name'		=> 'quote_manage',
				'text'		=> Lang::get('quote_manage'),
				'submenu'	=> array(
						'quote_index'=> array(
								'text'	=> Lang::get('quote_index'),
								'app'	=> 'quote',
								'act'	=> 'index',
								'name'	=> 'quote_index',
						),
						//         				'quote_success_order'=> array(
						//         						'text'	=> Lang::get('quote_success_order'),
						//         						'app'	=> 'quote',
						//         						'name'	=> 'quote_success_order',
						//         						'act'	=> 'success_order',
						//         				),
						'quote_history_list'=>array(
								'text'	=> Lang::get('quote_history_list'),
								'app'	=> 'quote',
								'name'	=> 'quote_history_list',
								'act'	=> 'history_list',
						)
				)
		);
		
		
		/* 样板管理 */
		$menu['sample_manage'] = array(
				'name'  => 'sample_manage',
				'text'  => Lang::get('sample_manage'),
				'submenu'   => array(
						'add_sample'  => array(
								'text'  => Lang::get('add_sample'),
								'app'   => 'sample',
								'name'  => 'add_sample',
						),
						'sample_reveal'  => array(
								'text'  => Lang::get('sample_reveal'),
								'app'   => 'sample',
								'act'	=> 'reveal',
								'name'  => 'sample_reveal',
						),
						'sample_info'  => array(
								'text'  => Lang::get('sample_info'),
								'app'   => 'sample',
								'act'	=> 'status',
								'name'  => 'sample_info',
						),
						/*'sourcing_task'  => array(
						 'text'  => Lang::get('sourcing_task'),
								'app'   => 'sourcing_task',
								'name'  => 'sample_info',
						),*/
						'sample_search'  => array(
								'text'  => Lang::get('sample_search'),
								'app'   => 'sample',
								'act'	=> 'search',
								'name'  => 'sample_search',
						)
				)
		);
		
		/* 采购管理 */
		$menu['purchase_manage'] = array(
				'name'		=> 'purchase_manage',
				'text'		=> Lang::get('purchase_manage'),
				'submenu'	=> array(
						'purchase_index'=> array(
								'text'	=> Lang::get('purchase_index'),
								'app'	=> 'purchase',
								'act'	=> 'index',
								'name'	=> 'purchase_index',
						),
						'purchase_status'=> array(
								'text'	=> Lang::get('purchase_status'),
								'app'	=> 'purchase',
								'name'	=> 'purchase_status',
								'act'	=> 'status',
						),
						// 				'purchase_bulk'=> array(
								// 					'text'	=> Lang::get('purchase_bulk'),
								// 					'app'	=> 'purchase',
								// 					'name'	=> 'purchase_bulk',
								// 					'act'	=> 'bulk',
								// 				),
						'purchase_sourcing_list'=>array(
								'text'	=> Lang::get('purchase_sourcing_list'),
								'app'	=> 'purchase',
								'name'	=> 'purchase_sourcing_list',
								'act'	=> 'sourcing_list',
						)
				)
		);
		
		/* 订单 */
		$menu['order_manage'] = array(
				'name'  => 'order_manage',
				'text'  => Lang::get('order_manage'),
				'submenu'   => array(
						'order_product'  => array(
								'text'  => Lang::get('order_product'),
								'app'   => 'order',
								'name'  => 'order_product',
								'act'  => 'status',
						),
						'order_list'  => array(
								'text'  => Lang::get('order_list'),
								'app'   => 'order',
								'name'  => 'order_list',
								'act'  => 'index',
						),
						'order_shipment'  => array(
								'text'  => Lang::get('order_shipment'),
								'app'   => 'order',
								'name'  => 'order_shipment',
								'act'  => 'shipment',
						),
						'order_ssapproved'  => array(
								'text'  => Lang::get('order_ssapproved'),
								'app'   => 'order',
								'name'  => 'order_ssapproved',
								'act'  => 'ssapproved',
						),
						'order_search'  => array(
								'text'  => Lang::get('order_search'),
								'app'   => 'order',
								'name'  => 'order_search',
								'act'  => 'search',
						),
						'order_statistics'  => array(
								'text'  => Lang::get('order_statistics'),
								'app'   => 'default',
								'name'  => 'order_statistics',
								'act'  => 'order_count',
						),
						'order_cargo_discount'  => array(
								'text'  => Lang::get('order_cargo_discount'),
								'app'   => 'order',
								'name'  => 'order_cargo_discount',
								'act'  => 'cargo_discount',
						),
						'order_store_return_goods'  => array(
								'text'  => Lang::get('order_store_return_goods'),
								'app'   => 'order',
								'name'  => 'order_store_return_goods',
								'act'  => 'store_return_goods',
						),
						'order_reconlist'  => array(
								'text'  => Lang::get('order_reconlist'),
								'app'   => 'order',
								'name'  => 'order_reconlist',
								'act'  => 'reconlist',
						),
						'order_moneylist'  => array(
								'text'  => Lang::get('order_moneylist'),
								'app'   => 'reconlist',
								'name'  => 'order_moneylist',
								'act'  => 'index',
						),
						'order_same_style'  => array(
								'text'  => Lang::get('order_same_style'),
								'app'   => 'order',
								'name'  => 'order_same_style',
								'act'  => 'same_style',
						),
						//             	'order_receipt_list'  => array(
								//             		'text'  => Lang::get('order_receipt_list'),
								//             		'app'   => 'order',
								//             		'name'  => 'order_receipt_list',
								//             		'act'  => 'receipt_list',
								//             	),
						/*'chuhuo'  => array(
						 'text'  => Lang::get('chuhuo'),
								'app'   => 'chuhuo',
								'name'  => 'chuhuo',
								'act'  => 'index',
						),*/
						'calc' => array(
								'name' => 'calc',
								'text' => Lang::get('calc'),
								'app' => 'calc',
								'act' => 'index',
								//'url' => "'factory','list',",
						)
						/*
						 'chuhuo_list' =>array(
						 		'text'  => Lang::get('chuhuo_list'),
						 		'app'   => 'order',
						 		'name'  => 'chuhuo_list',
						 		'act'  => 'chuhuo_list',
						 )*/
				)
		);
		
		/* 需求管理 */
		$menu['demand_manage'] = array(
				'name'		=> 'demand_manage',
				'text'		=> Lang::get('demand_manage'),
				'submenu'	=> array(
						'demand_list'=> array(
								'text'	=> Lang::get('demand_list'),
								'app'	=> 'merchant',
						),
						'history_demand'=> array(
								'text'	=> Lang::get('history_demand'),
								'app'	=> 'merchant',
								'act'	=> 'history_demand',
						)
				)
		);
		
		/*色卡信息*/
		$menu['color_card'] = array(
				'name'  => 'color_card',
				'text'  => Lang::get('color_card'),
				'app' => 'colorcard',
				'act' => 'index',
		);
		
		
		/* 评价管理 */
		$menu['evaluate_manage'] = array(
				'name'		=> 'evaluate_manage',
				'text'		=> Lang::get('evaluate_manage'),
				'submenu'	=> array(
						'history_evaluated'=> array(
								'text'	=> Lang::get('history_evaluated'),
								'app'	=> 'evaluate',
								'act'	=> 'history_evaluated',
						),
						'evaluate_total'=> array(
								'text'	=> Lang::get('evaluate_total'),
								'app'	=> 'evaluate',
								'act'	=> 'eval_total',
						)
				)
		);
		
		/* 客户跟进 */
		$menu['consumer_schedule'] = array(
				'name'		=> 'consumer_schedule',
				'text'		=> Lang::get('consumer_schedule'),
				'submenu'	=> array(
						'consumer_schedule'=> array(
								'text'	=> Lang::get('consumer_schedule'),
								'app'	=> 'schedule',
								'act'	=> 'index',
						),
						'consumer_list'=> array(
								'text'	=> Lang::get('consumer_list'),
								'app'	=> 'schedule',
								'act'	=> 'consumer_list',
						),
						'perf_total'=> array(
								'text'	=> Lang::get('perf_total'),
								'app'	=> 'schedule',
								'act'	=> 'perf_total',
						)
				)
		);
		
		/* 留言管理 */
		$menu['guestbook_manage'] = array(
				'name'		=> 'guestbook_manage',
				'text'		=> Lang::get('guestbook_manage'),
				'submenu'	=> array(
						'add_guestbook'	=> array(
								'text'	=> Lang::get('add_guestbook'),
								'app'	=> 'guestbook',
								'act'	=> 'add',
						),
						'guestbook_list'=> array(
								'text'	=> Lang::get('guestbook_list'),
								'app'	=> 'guestbook',
								'act'	=> 'index',
						)
				)
		);
        
          /* 系统设置 */
        $menu['system_setting'] = array(
            'name'  => 'system_setting',
            'text'  => Lang::get('system_setting'),
            'submenu'   => array(
				/*'upload_setting' => array(
					'text'	=> Lang::get('upload_setting'),
					'app'	=> 'upload_setting',
					'name'	=> 'upload_setting',
				),*/
            	'user_manage'	=> array(
            		'text'  => Lang::get('user_manage'),
            		'app'   => 'member',
            		'act'	=> 'user_list',
            		'name'  => 'user_manage',
            	),
                'member_manage'  => array(
                    'text'  => Lang::get('member_manage'),
                    'app'   => 'member',
                    'name'  => 'order_list',
                ),
			   'roles_manage'  => array(
                    'text'  => Lang::get('roles_manage'),
                    'app'   => 'member',
					'act'   => 'rolesman',
                    'name'  => 'roles_manage',
                ),
				'member_financepwdset'  => array(
                    'text'  => Lang::get('member_financepwdset'),
                    'app'   => 'member',
					'act'   => 'financepwdset',
                    'name'  => 'member_financepwdset',
                ),
                'buyer_manage'  => array(
                    'text'  => Lang::get('buyer_manage'),
                    'app'   => 'buyer',
                    'name'  => 'buyer_manage',
                ),
				'company_manage' =>array(
                    'text'  => Lang::get('company_manage'),
                    'app'   => 'company',
                    'name'  => 'company_manage',
                ),
            	'sling_manage' =>array(
            		'text'  => Lang::get('sling_manage'),
            		'app'   => 'sling',
            		'name'  => 'sling_manage',
            	),
            	'spare_button' =>array(
            		'text'  => Lang::get('spare_button'),
            		'app'   => 'spare',
            		'name'  => 'spare_button',
            	),
            	'package_demand' =>array(
            		'text'  => Lang::get('package_demand'),
            		'app'   => 'spare',
            		'name'  => 'package_demand',
            		'act'	=> 'package_demand'
            	),
                'brand_manage' =>array(
                    'text'  => Lang::get('brand_manage'),
                    'app'   => 'brand',
                    'name'  => 'brand_manage',
                ),
            	'main_label_manage' =>array(
            		'text'  => Lang::get('main_label_manage'),
            		'app'   => 'main_label',
            		'name'  => 'main_label_manage',
            	),
            	'listing_manage' =>array(
            		'text'  => Lang::get('listing_manage'),
            		'app'   => 'listing',
            		'name'  => 'listing_manage',
            	),
                'factory_manage'  => array(
                    'text'  => Lang::get('factory_manage'),
                    'app'   => 'factory',
                    'name'  => 'factory_manage',
                ),
            	'regions_manage'  => array(
            		'text'  => Lang::get('regions_manage'),
            		'app'   => 'region',
            		'name'  => 'regions_manage',
            	),
                'fabric_shop_manage'  => array(
                    'text'  => Lang::get('fabric_shop_manage'),
                    'app'   => 'fabric_shop',
                    'name'  => 'fabric_shop_manage',
                ),
            	'fabric_type_manage'  => array(
            		'text'  => Lang::get('fabric_type_manage'),
            		'app'   => 'fabric_shop',
            		'name'  => 'fabric_type_manage',
            		'act'	=> 'stall_type'
            	),
            	'color_characteristics'	=> array(
            		'name'  => 'color_characteristics',
            		'text'  => Lang::get('color_characteristics'),
            		'app' => 'colorcard',
            		'act' => 'color_characteristics',
            	),
            	'color_attr'	=> array(
            		'name'  => 'color_attr',
            		'text'  => Lang::get('color_attr'),
            		'app' => 'colorcard',
            		'act' => 'color_attr',
            	),
                 'calc'  => array(
                    'text'  => Lang::get('calc'),
                    'app'   => 'calc',
                    'name'  => 'manage',
                     'act'=>'manage'
                ),
				 'disreason'  => array(
                    'text'  => Lang::get('disreason_manage'),
                    'app'   => 'disreason',
                    'name'  => 'disreason_manage',
                     'act'=>'index'
                ),
				 'sizename'  => array(
                    'text'  => Lang::get('sizename_index'),
                    'app'   => 'sizename',
                    'name'  => 'sizename_index',
                     'act'=>'index'
                ),
            	'water_mark_manage' =>array(
            		'text'  => Lang::get('water_mark_manage'),
            		'app'   => 'water_mark',
            		'name'  => 'water_mark_manage',
            	),
                'style_manage'  => array(
                    'text'  => Lang::get('style_manage'),
                	'app'	=>'style',
                    'name'  => 'style_manage',
                )
            )
         );
         
		/* 绩效考核 
         $menu['perf_appr'] = array(
            'name'  => 'others',
            'text'  => Lang::get('perf_appr'),
            'submenu'   => array(
                'sourcing_appr'  => array(
                    'text'  => Lang::get('sourcing_appr'),
                    'app'   => 'sourcing_appr',
                    'name'  => 'sourcing_appr',
                ),
                'merchandiser_appr'  => array(
                    'text'  => Lang::get('merchandiser_appr'),
                    'app'   => 'merchandiser_appr',
                    'name'  => 'merchandiser_appr',
                ),
                'factory_appr' =>array(
                    'text'  => Lang::get('factory_appr'),
                    'app'   => 'factory_appr',
                    'name'  => 'special_manage',

                )
            )
        );*/
        
        /* 工厂联络表 */
        $menu['factory_manage'] = array(
        		'text' => Lang::get('factory_manage'),
        		'name' => 'factory_manage',
        		'submenu'   => array(
        			'factory_list'  => array(
        				'text'  => Lang::get('factory_list'),
        				'app'   => 'factory_list',
        				'name'  => 'factory_list',
        				'act'	=> 'index'
        			),
        			'factory_activation'  => array(
        				'text'  => Lang::get('factory_activation'),
        				'app'   => 'factory_list',
        				'name'	=> 'factory_activation',
        				'act'  => 'activation',
        			)
        		)
        );
        
        /* 档口联络表 */
        $menu['merchant_manage'] = array(
        		'text' => Lang::get('merchant_manage'),
        		'name' => 'merchant_list',
        		'submenu'   => array(
        			'merchant_list'  => array(
        				'text'  => Lang::get('merchant_list'),
        				'app'   => 'fabric_shop',
        				'name'  => 'factory_list',
        				'act'	=> 'merch_list'
        			),
        			'merchant_activation'  => array(
        				'text'  => Lang::get('merchant_activation'),
        				'app'   => 'fabric_shop',
        				'name'  => 'merchant_activation',
        				'act'	=> 'activation'
        			)
        		)
        );
        
        /* 员工联络表 */
        $menu['employee_list'] = array(
        		'text' => Lang::get('employee_list'),
        		'name' => 'employee_list',
        		'app' => 'employee',
        		'act' => 'index',
        		//'url' => "'factory','list',",
        );
		
		/* 用户设置 */
		$menu['member_data_info'] = array(
				'text'	=> Lang::get('member_data_info'),
				'app'	=> 'member',
				'act'	=> 'data_info',
				'name'	=> 'member_data_info',
		);
		
        return $menu;
    }
}

/**
 *    店铺管理子系统基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class StoreadminbaseApp extends MemberbaseApp
{
    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && !in_array(ACT, array('login', 'register', 'check_user','factory_register','go_register','merch_register')))
        {
            if (!IS_AJAX)
            {
                header('Location:index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

                return;
            }
            else
            {
                $this->json_error('login_please');
                return;
            }
        }
        $referer = $_SERVER['HTTP_REFERER'];
        if (strpos($referer, 'act=login') === false)
        {
            $ret_url = $_SERVER['HTTP_REFERER'];
            $ret_text = 'go_back';
        }
        else
        {
            $ret_url = SITE_URL . '/index.php';
            $ret_text = 'back_index';
        }

        /* 检查是否是店铺管理员 */
        if (!$this->visitor->get('manage_store'))
        {
            /* 您不是店铺管理员 */
            $this->show_warning(
                'not_storeadmin',
                'apply_now', 'index.php?app=apply',
                $ret_text, $ret_url
            );

            return;
        }

        /* 检查是否被授权 */
        $privileges = $this->_get_privileges();
        if (!$this->visitor->i_can('do_action', $privileges))
        {
            $this->show_warning('no_permission', $ret_text, $ret_url);

            return;
        }

        /* 检查店铺开启状态 */
        $state = $this->visitor->get('state');
        if ($state == 0)
        {
            $this->show_warning('apply_not_agree', $ret_text, $ret_url);

            return;
        }
        elseif ($state == 2)
        {
            $this->show_warning('store_is_closed', $ret_text, $ret_url);

            return;
        }

        /* 检查附加功能 */
        if (!$this->_check_add_functions())
        {
            $this->show_warning('not_support_function', $ret_text, $ret_url);
            return;
        }

        parent::_run_action();
    }
    function _get_privileges()
    {
        $store_id = $this->visitor->get('manage_store');
        $privs = $this->visitor->get('s');

        if (empty($privs))
        {
            return '';
        }

        foreach ($privs as $key => $admin_store)
        {
            if ($admin_store['store_id'] == $store_id)
            {
                return $admin_store['privs'];
            }
        }
    }
    
    /* 获取当前店铺所使用的主题 */
    function _get_theme()
    {
        $model_store =& m('store');
        $store_info  = $model_store->get($this->visitor->get('manage_store'));
        $theme = !empty($store_info['theme']) ? $store_info['theme'] : 'default|default';
        list($curr_template_name, $curr_style_name) = explode('|', $theme);
        return array(
            'template_name' => $curr_template_name,
            'style_name'    => $curr_style_name,
        );
    }

    function _check_add_functions()
    {
        $apps_functions = array( // app与function对应关系
            'seller_groupbuy' => 'groupbuy',
            'coupon' => 'coupon',
        );
        if (isset($apps_functions[APP]))
        {
            $store_mod =& m('store');
            $settings = $store_mod->get_settings($this->_store_id);
            $add_functions = isset($settings['functions']) ? $settings['functions'] : ''; // 附加功能
            if (!in_array($apps_functions[APP], explode(',', $add_functions)))
            {
                return false;
            }
        }
        return true;
    }
}

/**
 *    店铺控制器基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class StorebaseApp extends FrontendApp
{
    var $_store_id;

    /**
     * 设置店铺id
     *
     * @param int $store_id
     */
    function set_store($store_id)
    {
        $this->_store_id = intval($store_id);

        /* 有了store id后对视图进行二次配置 */
        $this->_init_view();
        $this->_config_view();
    }

    function _config_view()
    {
        parent::_config_view();
        /*$template_name = $this->_get_template_name();
        $style_name    = $this->_get_style_name();

        $this->_view->template_dir = ROOT_PATH . "/themes/store/{$template_name}";
        $this->_view->compile_dir  = ROOT_PATH . "/temp/compiled/store/{$template_name}";
        $this->_view->res_base     = SITE_URL . "/themes/store/{$template_name}/styles/{$style_name}";*/
        $this->_view->template_dir = ROOT_PATH . "/template";
        $this->_view->compile_dir  = ROOT_PATH . "/template/compiled";
        $this->_view->res_base     = SITE_URL . "/template/styles";
    }

    /**
     * 取得店铺信息
     */
    function get_store_data()
    {
        $cache_server =& cache_server();
        $key = 'function_get_store_data_' . $this->_store_id;
        $store = $cache_server->get($key);
        if ($store === false)
        {
            $store = $this->_get_store_info();
            if (empty($store))
            {
                $this->show_warning('the_store_not_exist');
                exit;
            }
            if ($store['state'] == 2)
            {
                $this->show_warning('the_store_is_closed');
                exit;
            }
            $step = intval(Conf::get('upgrade_required'));
            $step < 1 && $step = 5;
            $store_mod =& m('store');
            $store['credit_image'] = $this->_view->res_base . '/images/' . $store_mod->compute_credit($store['credit_value'], $step);

            empty($store['store_logo']) && $store['store_logo'] = Conf::get('default_store_logo');
            $store['store_owner'] = $this->_get_store_owner();
            $store['store_navs']  = $this->_get_store_nav();
            $goods_mod =& m('goods');
            $store['goods_count'] = $goods_mod->get_count_of_store($this->_store_id);
            $store['store_gcates']= $this->_get_store_gcategory();
            $store['sgrade'] = $this->_get_store_grade('grade_name');
            $functions = $this->_get_store_grade('functions');
            $store['functions'] = array();
            if ($functions)
            {
                $functions = explode(',', $functions);
                foreach ($functions as $k => $v)
                {
                    $store['functions'][$v] = $v;
                }
            }
            $cache_server->set($key, $store, 1800);
        }

        return $store;
    }

    /* 取得店铺信息 */
    function _get_store_info()
    {
        if (!$this->_store_id)
        {
            /* 未设置前返回空 */
            return array();
        }
        static $store_info = null;
        if ($store_info === null)
        {
            $store_mod  =& m('store');
            $store_info = $store_mod->get_info($this->_store_id);
        }

        return $store_info;
    }

    /* 取得店主信息 */
    function _get_store_owner()
    {
        $user_mod =& m('member');
        $user = $user_mod->get($this->_store_id);

        return $user;
    }

    /* 取得店铺导航 */
    function _get_store_nav()
    {
        $article_mod =& m('article');
        return $article_mod->find(array(
            'conditions' => "store_id = '{$this->_store_id}' AND cate_id = '" . STORE_NAV . "' AND if_show = 1",
            'order' => 'sort_order',
            'fields' => 'title',
        ));
    }
    /*  取的店铺等级   */

    function _get_store_grade($field)
    {
        $store_info = $store_info = $this->_get_store_info();
        $sgrade_mod =& m('sgrade');
        $result = $sgrade_mod->get_info($store_info['sgrade']);
        return $result[$field];
    }
    /* 取得店铺分类 */
    function _get_store_gcategory()
    {
        $gcategory_mod =& bm('gcategory', array('_store_id' => $this->_store_id));
        $gcategories = $gcategory_mod->get_list(-1, true);
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getArrayList(0);
    }

    /**
     *    获取当前店铺所设定的模板名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_template_name()
    {
        $store_info = $this->_get_store_info();
        $theme = !empty($store_info['theme']) ? $store_info['theme'] : 'default|default';
        list($template_name, $style_name) = explode('|', $theme);

        return $template_name;
    }

    /**
     *    获取当前店铺所设定的风格名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_style_name()
    {
        $store_info = $this->_get_store_info();
        $theme = !empty($store_info['theme']) ? $store_info['theme'] : 'default|default';
        list($template_name, $style_name) = explode('|', $theme);

        return $style_name;
    }
}

/* 实现消息基础类接口 */
class MessageBase extends MallbaseApp {};

/* 实现模块基础类接口 */
class BaseModule  extends FrontendApp {};

/* 消息处理器 */
require(ROOT_PATH . '/eccore/controller/message.base.php');

?>
